#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author : wzp
# date : modify by wzp 20220513

import sys
import datetime,time
sys.path.append("./lib")
from flask import Flask,request
from flask_restful import reqparse, abort, Api, Resource
from wechat import send_msg
from teambot import send_verification_code
from dto import toMYSQL
from global_info import *
import xml.etree.cElementTree as ET
from WXBizMsgCrypt3 import WXBizMsgCrypt
from MessageStream import read




def perform(content,sender="",applicaton_id=1000002):

    #####存数据库
    try:
        toMYSQL(sender,content)
        print("数据库保存成功")
    except Exception as e:
        print("保存数据库失败")
        print(e)

    #####发送到微信
    try:
        if sender != "" and sender is not None:
            content = content + " send from {}".format(sender)
        send_msg(content, application_id=applicaton_id)
        print("微信发送成功")
    except Exception as e:
        print("微信发送失败")
        print(e)

#zf<id>
class CMessage(Resource):
    def __init__(self):
        pass

    def get(self,id):
        parser = reqparse.RequestParser()
        parser.add_argument("sender")
        parser.add_argument("content")

        args = parser.parse_args()

        sender = args["sender"]
        content = args["content"]

        ## other goto test
        application_id = app_id_main_test
        ## 个人普通验证码
        if 2 == int(id): application_id = app_id_auth_code
        ## ICT验证码
        ## 增加了teambot的发送
        if 3 == int(id):
            application_id = app_id_ict_auth_code
            send_verification_code("{}提供了{}".format(sender,content))
        ## ICT告警
        if 4 == int(id): application_id = app_id_ict_monitor
        ## ICT 哑资源:
        if 5 == int(id): application_id = app_id_yaziyuan_monitor
        ## ICT 能源智慧大脑
        if 6 == int(id): application_id = app_id_nengyuan_monitor


        perform(content,sender,application_id)
        return "ok",200


    def post(self,id):
        self.get(id)

#zf
class CMessageStd(Resource):
    def __init__(self):
        pass

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("sender")
        parser.add_argument("content")

        args = parser.parse_args()
        sender = args["sender"]
        content = args["content"]
        perform(content,sender)
        return "ok",200


    def post(self):
        self.get()

#callback
class Message(Resource):
    def __init__(self):
        pass

    def get(self):
        wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID)
        args = request.args
        msg_signature = args.get("msg_signature")
        timestamp = args.get("timestamp")
        nonce = args.get("nonce")
        echostr = args.get("echostr")
        ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
        print(ret, sEchoStr)
        return sEchoStr, 200

    def post(self):
        wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID)

        msg_signature = request.args.get("msg_signature")
        timestamp = request.args.get("timestamp")
        nonce = request.args.get("nonce")
        data = request.data

        ret,sMsg = wxcpt.DecryptMsg(data,msg_signature,timestamp,nonce)
        print(ret,sMsg)

        xml_tree = ET.fromstring(sMsg)
        Content = xml_tree.find("Content").text
        FromUserName = xml_tree.find("FromUserName").text
        ToUserName = xml_tree.find("ToUserName").text
        AgentID = xml_tree.find("AgentID").text
        CreateTime = xml_tree.find("CreateTime").text
        MsgType = xml_tree.find("MsgType").text
        MsgId = xml_tree.find("MsgId").text

        sRespData = '''<xml><ToUserName>{}</ToUserName><FromUserName>{}</FromUserName><CreateTime>{}</CreateTime><MsgType>{}</MsgType><Content>{}</Content><MsgId>{}</MsgId><AgentID>{}</AgentID></xml>'''


        get_list = read(Content)
        content = "\n".join([ content+":"+datetime.datetime.strftime(date,'%Y-%m-%d %H:%M:%S') for content,date in get_list])

        print(ToUserName,FromUserName,CreateTime,MsgType,content,MsgId,AgentID)
        sRespData = sRespData.format(ToUserName,FromUserName,CreateTime,MsgType,content,MsgId,AgentID)
        print(sRespData)

        ret, sEncryptMsg = wxcpt.EncryptMsg(sRespData, nonce, timestamp)
        if (ret != 0):
            print("EncryptMsg err : {}".format(ret))
            return "", 200
        return sEncryptMsg, 200

